<!-- 拨打电话完整功能，请参考/pages/packages/sfcar/index/index 搜索'</privatenumber>' -->
<template>
	<view style="height: 100%">
		 <!-- 小黑框 -->
		 <view style="position: relative; z-index: 9999999999">
            <toast id="toast" ref="toasts"></toast>
        </view>
		<!-- 选择支付方式 弹窗（付费，广告） -->
		<view :class="{'rewardadvPop':true, 'rewardadvShow':showRewardPop}" v-if="cfg_payPhone.wxmini && uniPlatform == 'mp-weixin' || (uniPlatform == 'web' && android && cfg_payPhone.tencentGDP_placement_id && cfg_payPhone.tencentGDP_app_id)">
			<view class="rewardAdvContent">
				<view class="rewardAdvCon">
					<view class="rewardClose" @click="showRewardPop = false">×</view>
					<view class="h3">看广告免费获取联系方式</view>
					<view class="p">{{!cfg_payPhone.payPhone_entrance ? '观看广告，或直接付费获取对方联系电话' : '观看广告免费获取对方联系电话'}}</view>
				</view>
				<view class="btns_group">
					<view class="btn_pay" v-if="!cfg_payPhone.payPhone_entrance" @click="callByPay">
						<view class="txt" >直接付费</view>
						<view class="span">
							<text class="symbol">{{ currency.symbol }}</text>
							<text class="amount">{{ payInfo.order_amount }}</text>
						</view>
					</view>
					<view class="btn_watch" @click="callBgAdv"> 
						<view class="txt">免费获取</view>
						<image class="img" :src="imgPath + '/payPop/video_icon.png?v=' + imgVersion" mode="aspectFill"></image>
					</view>
				</view>
			</view>
			<view class="rewardAdvMask" data-type="close" @click="showRewardPop = false"></view>
		</view>

		<view :class="'privatenumber-popup ' + (phoneData.showPrivateNumber ? 'privatenumber-show' : '')">
			<view class="privatenumber-content">
				<view class="privatenumber-header">
					<view class="privatenumber-title">请使用{{ phoneData.privateNumberFrom }}拨打</view>
					<view class="privatenumber-tips">
						<text>我们将为您使用虚拟号码拨出</text>
						<button class="privatenumber-otherphone" type="primary"
							:data-module="phoneData.privateNumberDataSet.module"
							:data-temp="phoneData.privateNumberDataSet.temp"
							:data-aid="phoneData.privateNumberDataSet.aid" open-type="getPhoneNumber"
							@getphonenumber="useOtherPhoneNumber" v-if="false">
							使用其他号码？
						</button>
					</view>
					<button class="privatenumber-close" data-type="close" @click="privatenumberClick">×</button>
				</view>
				<view class="privatenumber-main">
					<view class="privatenumber-phone">{{ phoneData.privateNumberPhone }}</view>
					<view class="privatenumber-text">
						此号码将在
						<text class="privatenumber-countdown">{{ phoneData.privateNumberCountDown }}秒</text>
						后失效，请尽快拨打
					</view>
				</view>
				<button class="privatenumber-btn" data-type="call" :data-phone="phoneData.privateNumberPhone"
					@click="privatenumberClick">立即拨打</button>
				<view class="concat_tip" v-if="globalData.appConfig && globalData.appConfig.cfg_shortname">联系我时，请说是在<text class="span">{{globalData.appConfig.cfg_shortname}}</text>上看到的，谢谢！</view>
			</view>
			<view class="privatenumber-mask" data-type="close" @click="privatenumberClick"></view>
		</view>
		<view :class="'privatenumber-popup ' + (phoneData.showhasPayNumber ? 'privatenumber-show' : '')">
			<view class="privatenumber-content">
				<view class="privatenumber-header">
					<view class="privatenumber-title">已获取联系方式，请尽快拨打</view>
					<view class="privatenumber-tips">
						<text>温馨提示，您可截图保存联系方式到相册</text>
					</view>
					<button class="privatenumber-close" data-type="close" @click="privatenumberClick">×</button>
				</view>
				<view class="privatenumber-main">
					<view class="privatenumber-phone">{{phoneData.privateNumberPhone }}</view>
					<view class="privatenumber-text">{{ phoneData.privateNumberPhoneTip }}</view>
				</view>
				<button class="privatenumber-btn" data-type="call" :data-phone="phoneData.privateNumberPhone"
					@click="privatenumberClick">立即拨打</button>
				<view class="concat_tip" v-if="globalData.appConfig && globalData.appConfig.cfg_shortname">联系我时，请说是在<text class="span">{{globalData.appConfig.cfg_shortname}}</text>上看到的，谢谢！</view>
			</view>
			<view class="privatenumber-mask" data-type="close" @click="privatenumberClick"></view>
		</view>
	</view>
</template>

<script>
	const app = getApp();
	export default {
		emits:['topay','haspay','showhasPayNumber','showPrivateNumber'],
		data(){
			return{
				showRewardPop:false,
				masterDomain:app.globalData.masterDomain,
				imgPath:app.globalData.imgPath,
				imgVersion:app.globalData.imgVersion,
				cfg_payPhone:{
					payPhone_entrance:0,
					payPhone_price:1,
					wxmini:'adunit-078d0de41e6925bf',
				},
				currency:{
					short:'元',
					symbol:'￥'
				},
				rewardedVideoAd:'',
				uniPlatform:'',
				android:app.globalData.platForm == 'web' ? window.Android : false,
				interval:null,
				globalData:app.globalData,
				clickTime:0, //点击拨打按钮的时间  以便计算时间差
			}
		},
		props: {
			phoneData: {
				type: Object,
				default: {
					privateNumberPhone: '',
					privateNumberCountDown: 0,
					showhasPayNumber: 0,
					privateNumberPhoneTip: '',
					showPrivateNumber: 0,
					privateNumberFrom: 0,
					privateNumberDataSet: {
						module: '',
						temp: '',
						aid: ''
					},
				}
			},

			// 支付信息 ，此处是为验证广告播放完成之后 是否算是支付成功
			payInfo: {
				//支付密码弹窗显示
				type: Object,
				default: {
					order_amount: '',
					order_sn: '',
					ordernum: '',
					service: '',
					timeout: 0
				}
			},
			
			
		},
		watch:{
			showRewardPop:function(val){
				const that = this;
				if(val){
					that.clickTime = parseInt(new Date().valueOf() / 1000)
					if(that.uniPlatform == 'web' && app.globalData.appBoolean && window.Android){
						// app端
					}else if(that.uniPlatform == 'mp-weixin'){
						that.initRewardAdv()
					}else {
						that.callByPay(); //应该调起支付
					}
				}
			}
		},
		mounted(){
			const that = this;
			that.$nextTick(() => {
				that.uniPlatform = app.globalData.platForm
				setTimeout(() => {
					if(app.globalData.appConfig){
						that.cfg_payPhone = app.globalData.appConfig.cfg_payPhone
						that.currency = app.globalData.appConfig.currency;
					}
				}, 1500);
			})
			
		},
		methods: {
			privatenumberClick(event) {
				var type = event.currentTarget.dataset.type;
				if (type == 'close') {
					this.$emit('showPrivateNumber', 0);
					this.$emit('showhasPayNumber', 0);
				} else if (type == 'call') {
					var phone = event.currentTarget.dataset.phone;
					if(app.globalData.appBoolean && app.globalData.platForm == 'web'){ //app端h5
						window.location.href = 'tel:' + phone
					}else{
						uni.makePhoneCall({
							phoneNumber: phone
						});
					}
					
				}
			},

			// 通过付费 拨通号码
			callByPay(){
				const that = this;
				let now = parseInt(new Date().valueOf() / 1000);
				let offTime = (now - that.clickTime)
				that.$emit('topay',offTime);
				that.showRewardPop = false;	
		
			},

			// 通过激励视频 拨通号码
			callBgAdv(){
				const that = this;
				that.showRewardPop = false;	
				if(app.globalData.appBoolean && window.Android){
					window.setupWebViewJavascriptBridge(function (bridge) {
                        bridge.callHandler("playRewardAd", { 'value': that.payInfo.ordernum }, function (responseData) { 
                            if(responseData == 'success'){
								that.interval = setInterval(() => {
									that.getPhoneInfo()
								},1000)
								
                            }
                        });
                    })
				}else{

					that.rewardedVideoAd.show()
					.catch(() => {
						that.rewardedVideoAd.load()
						.then(() => that.rewardedVideoAd.show())
						.catch(err => {
							let tip = !that.cfg_payPhone.payPhone_entrance ? '广告拉取失败，请稍后重试':'广告拉取失败，请支付后查看或者稍后重试'
							that.$refs.toasts.showToast(tip)
						})
					});
				}
			},

			initRewardAdv(){
				const that = this;
				if(that.rewardedVideoAd) return false; //已经初始化
				if(wx.createRewardedVideoAd){
					that.rewardedVideoAd = wx.createRewardedVideoAd({ adUnitId: that.cfg_payPhone.wxmini })
					that.rewardedVideoAd.onLoad(() => {
						console.log('onLoad event emit')
					})
					that.rewardedVideoAd.onError((err) => {
						console.log('onError event emit', err)
						// that.$refs.toasts.showToast('广告拉取失败')
						that.updatePlayState(2)
					})
					that.rewardedVideoAd.onClose((res) => {
						console.log('onClose event emit', res)
						// 用户点击了【关闭广告】按钮
						if (res && res.isEnded) {
							that.showRewardPop = false; //关闭弹窗
						// 正常播放结束，可以下发游戏奖励
							that.updatePlayState(1)
						} else {
						// 播放中途退出，不下发游戏奖励
						}
					})
				}
			},


			// 告诉服务端 播放完毕
			updatePlayState(playState){
				const that = this;
				uni.login({
					success:res => {
						var code = res.code;
						var dataPrarm = 'service=siteConfig&action=wxminiAdRewardVideoNotify&ordernum=' + that.payInfo.ordernum+'&code=' + code + '&state=' + playState;
						var urlData = app.encodeUrl(dataPrarm);
						that.$ajax.post({
							url: 'include/ajax.php?' + urlData,
						}).then(res => {
							if(playState == 1){
								that.getPhoneInfo()
							}
						})
					}
				})
			},

			// 验证是否支付成功 
			getPhoneInfo() {
				const that = this
				var dataPrarm = 'service=member&action=tradePayResult&order=' + that.payInfo.ordernum;
				var urlData = app.encodeUrl(dataPrarm);
				that.$ajax.post({
					url: 'include/ajax.php?' + urlData,
				}).then(res => {
					var data = res.data;
					if (data.state == 100) {
						if(that.interval){
							clearInterval(that.interval)
						}
						that.$emit('haspay', {
							detail: data,
							fromAdv:1, //此处表示通过广告拨打电话
						}); 
					}else{
						// if(that.uniPlatform == 'web' && app.globalData.appBoolean && window.Android){
						// 	alert(data.info)
						// }
					}
				})
			},
		},
	}
</script>
<style>
	@import './privatenumber.css';
</style>